package cn.yuitstyle.excel;

import cn.yuitstyle.excel.annotation.*;
import cn.yuitstyle.excel.exception.ExcelException;

import java.lang.reflect.Field;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * excel格式校验
 */
public class ExcelImportValid {

    public static void valid(Object object) {
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            //设置可访问
            field.setAccessible(true);
            //属性的值
            Object fieldValue;
            try {
                fieldValue = field.get(object);
            } catch (IllegalAccessException e) {
                throw new ExcelException( "IMPORT_PARAM_CHECK_FAIL");
            }
            //是否包含必填校验注解
            boolean isExcelNotNull = field.isAnnotationPresent(ExcelNotNull.class);
            if (isExcelNotNull && Objects.isNull(fieldValue)) {
                throw new ExcelException( field.getAnnotation(ExcelNotNull.class).message());
            }
            // 长度校验
            boolean isExcelLength = field.isAnnotationPresent(ExcelLength.class);
            if (isExcelLength) {
                int max = field.getAnnotation(ExcelLength.class).max();
                if (fieldValue.toString().length() > max) {
                    throw new ExcelException( field.getAnnotation(ExcelLength.class).message());
                }
                int min = field.getAnnotation(ExcelLength.class).min();
                if (fieldValue.toString().length() < min) {
                    throw new ExcelException( field.getAnnotation(ExcelLength.class).message());
                }
            }
            // 正则校验
            boolean isExcelPattern = field.isAnnotationPresent(ExcelDigitPattern.class);
            if (isExcelPattern) {
                String pattern = field.getAnnotation(ExcelDigitPattern.class).pattern();
                Pattern compile = Pattern.compile(pattern);
                if (!compile.matcher(fieldValue.toString()).matches()) {
                    throw new ExcelException( field.getAnnotation(ExcelDigitPattern.class).message());
                }
            }
            // 校验是否数值超过上限
            boolean isExcelMax = field.isAnnotationPresent(ExcelMax.class);
            if (isExcelMax) {
                long value = field.getAnnotation(ExcelMax.class).value();
                if (Long.parseLong(fieldValue.toString()) > value) {
                    throw new ExcelException( field.getAnnotation(ExcelMax.class).message());
                }
            }
            // 校验是否数值低于下限
            boolean isExcelMin = field.isAnnotationPresent(ExcelMin.class);
            if (isExcelMin) {
                long value = field.getAnnotation(ExcelMax.class).value();
                if (Long.parseLong(fieldValue.toString()) < value) {
                    throw new ExcelException( field.getAnnotation(ExcelMax.class).message());
                }
            }

        }
    }

}
